package com.almeros.ohos.multitouch.library;

import ohos.multimodalinput.event.TouchEvent;

import java.math.BigDecimal;

/**
 * @author Almer Thie (code.almeros.com)
 * Copyright (c) 2013, Almer Thie (code.almeros.com)
 */
public class MoveGestureDetector {

    private static final int INVALID_POINTER_INDEX = -1;
    private int mPointerIndex;
    private OnMoveGestureListener mListener;
    private float lastX;
    private float lastY;
    private float tempX;
    private float tempY;

    public MoveGestureDetector(OnMoveGestureListener listener) {
        mListener = listener;
        mPointerIndex = INVALID_POINTER_INDEX;
    }

    public float getX() {
        return tempX;
    }

    public float getY() {
        return tempY;
    }

    public boolean onTouchEvent(TouchEvent event) {
        switch (event.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                lastX = event.getPointerPosition(0).getX();
                lastY = event.getPointerPosition(0).getY();
                mPointerIndex = event.getPointerId(0);
                break;
            case TouchEvent.POINT_MOVE:
                if (mPointerIndex != INVALID_POINTER_INDEX && event.getPointerCount() != 0) {
                    float mX = event.getPointerPosition(0).getX();
                    float mY = event.getPointerPosition(0).getY();
                    BigDecimal bignum1 = new BigDecimal(mX);
                    BigDecimal bignum2 = new BigDecimal(lastX);
                    BigDecimal bignum3 = new BigDecimal(mY);
                    BigDecimal bignum4 = new BigDecimal(lastY);
                    float value = bignum1.subtract(bignum2).floatValue();
                    float value2 = bignum3.subtract(bignum4).floatValue();
                    if (Math.abs(value) > 3 && Math.abs(value2) > 3) {
                        BigDecimal bignum5 = new BigDecimal(tempX);
                        tempX = bignum5.add(bignum1.subtract(bignum2)).floatValue();
                        if (Math.abs(value2) < 100) {
                            BigDecimal bignum6 = new BigDecimal(tempY);
                            tempY = bignum6.add(bignum3.subtract(bignum4)).floatValue();
                        }
                        if (mListener != null) {
                            mListener.onMove(this);
                        }
                        lastX = mX;
                        lastY = mY;
                    }
                }
                break;
            case TouchEvent.PRIMARY_POINT_UP:
                mPointerIndex = INVALID_POINTER_INDEX;
                break;
        }
        return true;
    }

    public static class SimpleOnScaleGestureListener implements OnMoveGestureListener {

        @Override
        public boolean onMove(MoveGestureDetector scaleDetector) {
            return false;
        }
    }

    public interface OnMoveGestureListener {

        boolean onMove(MoveGestureDetector scaleDetector);
    }
}
